package com.yuyou.fn.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yuyou.fn.common.service.IWxTemplateMessage;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class WxTemplateMessageImpl implements IWxTemplateMessage {
	
	private final static Logger log = LoggerFactory.getLogger(WxTemplateMessageImpl.class);
	
	String MODEL_MESSAGE_URL = "http://wx.yuyou100.com/wechat/sendTemplateMessage";

	@Override
	public boolean send(String templateId, String toOpenId, String url, List<Map<String, Object>> params) {
		OkHttpClient client = new OkHttpClient();
		
		JSONObject json  = new JSONObject();
		json.put("data", params);
		json.put("template_id", templateId);
		json.put("toUser", toOpenId);
		json.put("url", url);

		Request request = new Request.Builder().url(MODEL_MESSAGE_URL)
				.post(new FormBody.Builder().addEncoded("templateMessageJson", json.toJSONString() ).build()).addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").build();

		Response response = null ;
		try {
			response = client.newCall(request).execute();
		} catch (IOException e) {
			log.error("Send wx template fail !",  e  );
			return false ;
		}finally {
			if(response != null ){
				response.close();
			}
		}
		return true;
		
	}

}
